var IndexStatDetail = {
    layerIndex: -1,
};
$(function () {
    $.parser.parse(); // 解析整个页面
    var curDate = getNowFormatDate();
    Common_SetValue('SDate', curDate);
    Common_SetValue('EDate', curDate);
    $HUI.combobox('#DateType',
        {
            data:[
                {'DateType':'InEntiy','Desc':"入组日期"},
                {'DateType':'UpQC','Desc':"上报日期"},
                {'DateType':'OutHosp','Desc':"出院日期"}
            ],
            valueField:'DateType',
            textField:'Desc',
        })
    Common_SetValue('DateType','UpQC');
    $HUI.combobox('#Hospital',
        {
            data:$.parseJSON($("#officeMap").val()),
            valueField:'value',
            textField:'text',
            defaultFilter: 6,
            onSelect:IndexStatDetail.officeChange,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                var val = $(this).combobox("getData");
                if(val.length==2){//如果就一个院区 加上全部=2
                    $(this).combobox("setValue", val[1].value);
                    PortalMrlist.officeChange(val[1]);
                    $("#oneOffice").val("yes");
                }else{
                    $(this).combobox("setValue", "");
                    $("#oneOffice").val("no");
                }
            }
        } )
    $HUI.combobox('#LocDic',
        {
            data:$.parseJSON($("#departMap").val()),
            valueField:'value',
            textField:'text',
            defaultFilter: 6
            //目前主任医师和科室无关联
            //onSelect:PortalMrlist.LocChange
        })
    $HUI.combobox('#Status',
        {
            /*data:$.parseJSON($("#statusMap").val()),*/
            data:[
                {'state':'Check','Desc':"审核"},
                {'state':'Up','Desc':"已上报"},
                {'state':'Submit','Desc':"提交"}
            ],
            valueField:'state',
            textField:'Desc',
            defaultFilter: 6,
            multiple:true,
            rowStyle:'checkbox', //显示成勾选行形式
            selectOnNavigation:false,
            blurValidValue:true,
            panelHeight:"auto",
            editable:false
        })
    $HUI.combobox('#DocDic',
        {
            data:$.parseJSON($("#docMap").val()),
            valueField:'value',
            textField:'text',
            defaultFilter: 6
        })
    $HUI.combobox('#QCDic',
        {
            data:$.parseJSON($("#entityMap").val()),
            valueField:'value',
            textField:'text',
            defaultFilter: 6,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                var val = $(this).combobox("getData");
                $(this).combobox("setValue", val[1].value);
            }
        })
    $('#search').on('click', function () {
        $('#home').layout('collapse','north');
        IndexStatDetail.drawTable(1,0);
    });
    //绘制标统计表格
    var ids = $("#ids").val();
    var qcEntity = $("#qcEntity").val();
    Common_SetValue('QCDic', qcEntity);
    //var data = JSON.parse(QCRows);
    IndexStatDetail.drawTable(ids,qcEntity);
    $("#entityDesc").panel({title:"单病种指标统计表格数据"});
});

IndexStatDetail.officeChange = function(that){
    var ajax = new $ax(Sys.backendPath + "/cdc/cdclocation/listLocationByHospID", function(data){
        var data = $.parseJSON(data.message);
        $('#depart').combobox({
            data:data,
            valueField:'value',
            textField:'text',
            defaultFilter: 6,
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                $(this).combobox("setValue", "");
            }
        });
    },function(data){
        layer.msg("查询失败!" + data.responseJSON.message + "!",{icon: 2});
    });
    ajax.set({"hospID":that.value,"id":"depart"});
    ajax.start();
}

IndexStatDetail.drawTable = function(data,qcEntity){



    var columns = [],
        initColumns = [],//公共固定列
        itemColumns = []; //动态因子列
    initColumns = [
        {title: '姓名', field: 'name', align: 'left', valign: 'middle', sortable: true,width:80,rowspan: 2,
            footerFormatter:function(value){
                return "总计";
            }
        }
    ];

    if (data==1) {
        //检索框查询
        var StatusStr = $('#Status').combobox('getValues').join(',');
        var params = {};
        var ajax = new $ax(Sys.backendPath + "/analysis/indexstat/selectIndexDetailTableData", function (detailData) {
            data = detailData;
        }, function (data) {
        });
        params.aStatus = StatusStr;
        params.aHospID = Common_GetValue('Hospital');
        params.aLocID  = replaceValue(Common_GetValue('LocDic'));
        params.aLocDesc = replaceValue(Common_GetText('LocDic'));
        params.aDocDesc = replaceValue(Common_GetText('DocDic'));
        params.aQCEntity = replaceValue(Common_GetText('QCDic'));
        params.qcEntity = Common_GetValue('QCDic');
        params.aDateFrom = Common_GetValue('SDate');
        params.aDateTo = Common_GetValue('EDate');
        params.aDateType = Common_GetValue('DateType');
        ajax.set(params);
        ajax.start();
    }else {
        var params = {};
        var ajax = new $ax(Sys.backendPath + "/analysis/indexstat/selectIndexDetailTableData", function (detailData) {
            data = detailData;
        }, function (data) {
        });
        params.ids = data;
        params.qcEntity = qcEntity;
        ajax.set(params);
        ajax.start();
    }
    var dataA = data.tableColumnAs;
    var dataB = data.tableColumnBs;
    var dataTable = data.tableDates;
    //查询病种对应一级表头
    for (var i = 0; i < dataA.length; i++){
        initColumns.push (
            {
                field: "",
                title: dataA[i].title ,
                width: dataA[i].colspan * 150,
                align: "center",
                halign: "center",
                colspan: dataA[i].colspan
            }
        );
    }
    //查询病种对应二级表头
    for (var i = 0; i < dataB.length; i++){
        let fieldNum = dataB[i].field;
        if (dataB[i].parentId==0){
            initColumns.push (
                {
                    field: dataB[i].field,
                    title: dataB[i].title ,
                    width: 150,
                    align: "left",
                    valign: 'middle',
                    rowspan: 2
                    /*footerFormatter:function(value){
                        return IndexStatDetail.sumFieldValue(value,fieldNum);
                    }*/
                }
            );
        }else {
            itemColumns.push (
                {
                    field: dataB[i].field,
                    title: dataB[i].title ,
                    width: 150,
                    align: "left",
                    valign: 'middle'
                    /*footerFormatter:function(value){
                        return IndexStatDetail.sumFieldValue(value,fieldNum);
                    }*/
                }
            );
        }
    }

    //住院日期不参与计算，直接取值，避免造成数据不一致
    initColumns.push (
        {
            field: "admDays",
            title: "住院天数" ,
            width: 150,
            align: "left",
            valign: "middle",
            rowspan: 2
            /*footerFormatter:function(value){
                return IndexStatDetail.sumFieldValue(value,"admDays");
            }*/
        }
    );
    columns.push(initColumns, itemColumns); //合并表格内容
    this.$table =
        $('#indexStatTable').bootstrapTable('destroy').bootstrapTable({
            data:dataTable,
            striped: false,//是否显示行间隔色
            pagination: false,//是否显示分页
            showFooter: false,
            //paginationLoop: false,
            //pageSize : 5,//用于设置每页初始显示的条数
            //pageList :[4],
            //sidePagination: 'server',//设置在哪进行分页，默认”client”，可选”server”,返回数据模板不同
            sortName: "patientNum",
            sortOrder: 'desc',// desc  asc
            maintainSelected: true,//设为true 为选中的状态
            cache: false,
            search: false, //搜索框
            columns: columns,
            onPostHeader: function(){  //当<thead></thead>中的内容被加载完后或者在你所用的DOM中有定义则被触发
                // $(".th-inner").css("font-weight","700");//表头字体加粗
                $("#indexStatTable > tbody td").each(function(index){//鼠标悬浮 显示表格数据
                    $(this).attr("title",$(this).text());
                });
            },
            onPostBody:function (dataTable) {
                merge_footer();
            },
        });


};

IndexStatDetail.sumFieldValue = function(value,field){
    var disSum = 0;
    var count = 0;
    var tem = 0;
    if (field.indexOf("Fee") >= 0){
        for(var i in value){
            if (value[i][field] == "未做"){
                continue;
            }
            count += value[i][field]*100;
            //disSum += parseInt(value[i]["num"])*100;
        }
        count = count/100;
        return (count).toFixed(2);
    }else if (field.indexOf("Time") >= 0){
        for(var i in value){
            if (value[i][field] != "否"){
                count += value[i][field];
            }
        }
        if (count == 0){
            return "0";
        }
        return count;
    } else if (field.indexOf("Value") >= 0){
        return "";
    } else if (field.indexOf("Days") >= 0){
        for(var i in value){
            count += value[i][field];
        }
        return count;
    } else {
        for(var i in value){
            if (value[i][field] == "是"){
                count += 1;
            }
        }
        if (count == 0){
            return "0";
        }
        return count;
    }

};

//设置合计列宽度
function merge_footer(){
    //获取table表中footer 并获取到这一行的所有列
    var footer_tbody = $('.fixed-table-footer table tbody');
    var footer_tr = footer_tbody.find('>tr');
    var footer_td = footer_tr.find('>td');
    var footer_td_1 = footer_td.eq(0);
    for(var i=0;i<footer_td.length;i++){
        footer_td.eq(i).hide();//隐藏单元格
        if(i == 0){
            footer_td.eq(i).attr('width', "80px").show();//显示单元格并设置列宽
        }else {
            footer_td.eq(i).attr('width', "150px").show();//显示单元格并设置列宽
        }
    }
}

function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    return currentdate;
}

//赋值
function Common_SetValue()
{
    var itmValue = '';

    var val = arguments[1];
    var txt = arguments[2];

    if (typeof(arguments[0]) !== 'string') return '';
    if (arguments[0] == '') return '';

    var $this = $('#'+ arguments[0]);
    if ($this.length < 1) return '';
    if (typeof val == 'undefined') val = '';
    if (typeof txt == 'undefined') txt = '';

    var className = $this.attr("class").split(' ')[0];

    if (className == 'textbox') {  //文本框
        itmValue = $this.val(val);
    }else if (className == 'hisui-numberbox') {  //数字
        itmValue = $this.val(val);
    }else if (className == 'hisui-datebox') {  //日期
        itmValue = $this.datebox('setValue',val);
    }else if (className == 'hisui-timespinner') {  //时间框
        itmValue = $this.timespinner('setValue',val);
    }else if (className == 'hisui-combobox') {  //下拉框
        if(val !="" && txt ==""){
            itmValue = $this.combobox('setValue',val);
        }else{
            itmValue = $this.combobox('setValue',txt);
        }
    }else if (className == 'hisui-switchbox') {  //开关
        itmValue = $this.switchbox('setValue',val);
    }else if (className == 'hisui-checkbox') {  // 单个复选框
        if (val == '') val = 0;
        itmValue = $this.checkbox('setValue',(val) ? true : false);
    }else if (className == 'hisui-radio') {  //单个单选框
        if (val == '') val = 0;
        itmValue = $this.radio('setValue',(val) ? true : false);
    }else if (className == 'hisui-searchbox') {  //查询框框
        itmValue = $this.searchbox('setValue',val);
    }

    return itmValue;
}


//取值
function Common_GetValue()
{
    var itmValue = '';

    if (typeof(arguments[0]) !== 'string') return '';
    if (arguments[0] == '') return '';

    var $this = $('#'+ arguments[0]);
    if ($this.length < 1) return '';

    var className = $this.attr("class").split(' ')[0];

    if (className == 'textbox') {  //文本框
        itmValue = $this.val();
    }else if (className == 'hisui-numberbox') {  //数字
        itmValue = $this.val();
    }else if (className == 'hisui-datebox') {  //日期
        itmValue = $this.datebox('getValue');
    }else if (className == 'hisui-timespinner') {  //时间框
        itmValue = $this.timespinner('getValue');
    }else if (className == 'hisui-combobox') {  //下拉框（多选下拉框没有封装）
        itmValue = $this.combobox('getValue');
    }else if (className == 'hisui-switchbox') {  //开关
        itmValue = $this.switchbox('getValue');
    }else if (className == 'hisui-checkbox') {  // 单个复选框
        itmValue = $this.checkbox('getValue');
    }else if (className == 'hisui-radio') {  //单个单选框
        itmValue = $this.radio('getValue');
    }else if (className == 'hisui-searchbox') {  //查询框框
        itmValue = $this.searchbox('getValue');
    }

    return itmValue;
}

//值为全部替换为空
function replaceValue(text) {
    if ("全部"==text) {
        return ""
    }else {
        return text;
    }
}

function Common_GetText()
{
    var itmValue = '';

    if (typeof(arguments[0]) !== 'string') return '';
    if (arguments[0] == '') return '';

    var $this = $('#'+ arguments[0]);
    if ($this.length < 1) return '';

    var className = $this.attr("class").split(' ')[0];

    if (className == 'textbox') {  //文本框
        itmValue = $this.val();
    }else if (className == 'hisui-numberbox') {  //数字
        itmValue = $this.val();
    }else if (className == 'hisui-datebox') {  //日期
        itmValue = $this.datebox('getValue');
    }else if (className == 'hisui-timespinner') {  //时间框
        itmValue = $this.timespinner('getValue');
    }else if (className == 'hisui-combobox') {  //下拉框
        itmValue = $this.combobox('getText');
    }else if (className == 'hisui-switchbox') {  //开关
        itmValue = $this.switchbox('getValue');
    }else if (className == 'hisui-checkbox') {  // 单个复选框
        itmValue = $this.attr("label");
    }else if (className == 'hisui-radio') {  //单个单选框
        itmValue =$this.attr("label");
    }else if (className == 'hisui-searchbox') {  //查询框框
        itmValue = $this.searchbox('getValue');
    }

    return itmValue;
}

/**
 * 导出主页的表格数据
 */
IndexStatDetail.exportTable = function() {
    var qcEntity = Common_GetText('QCDic');
    $("#tableDiv table").tableExport(
        {
            type : 'xlsx',
            escape : 'false',
            fileName : IndexStatDetail.getSystemTime()+qcEntity+'指标统计详情表'
        },IndexStatDetail.getSystemTime()+qcEntity+'指标统计表'
    )
};

/**
 * 获取当天年月日
 */
IndexStatDetail.getSystemTime = function(){
    function p(s) {
        return s < 10 ? '0' + s: s;
    }
    var date = new Date(); // 获取中国标准时间
    var y = date.getFullYear(); // 年
    var m = date.getMonth()+1; // 月
    var d = date.getDate(); // 日
    var sysTime = y+'-'+p(m)+'-'+p(d);
    return sysTime;
};